package xrc.rabbitmq;

import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import xrc.pojo.SecKillMessage;
import xrc.pojo.SeckillOrder;
import xrc.pojo.User;
import xrc.service.IGoodsService;
import xrc.service.IOrderService;
import xrc.utils.JsonUtil;
import xrc.vo.GoodsVO;
import xrc.vo.RespBean;
import xrc.vo.RespBeanEnum;

/**
 * 消息消费者
 */

@Service
@Slf4j
public class MQReceiver {

    // @RabbitListener(queues = "xxx") 应与配置类中 final 变量保持一致
    /*@RabbitListener(queues = "queue")
    public void receive(Object msg) {
        log.info("receive message : {}" + msg);
    }

    @RabbitListener(queues = "queue_fanout01")
    public void receive01(Object msg) {
        log.info("QUEUE01 receive message : {}" + msg);
    }

    @RabbitListener(queues = "queue_fanout02")
    public void receive02(Object msg) {
        log.info("QUEUE02 receive message : {}" + msg);
    }

    @RabbitListener(queues = "queue_direct01")
    public void receive03(Object msg) {
        log.info("QUEUE01 receive direct message : {}" + msg);
    }

    @RabbitListener(queues = "queue_direct02")
    public void receive04(Object msg) {
        log.info("QUEUE02 receive direct message : {}" + msg);
    }

    @RabbitListener(queues = "queue_topic01")
    public void receive05(Object msg) {
        log.info("QUEUE01 receive direct message : {}" , msg);
    }

    @RabbitListener(queues = "queue_topic02")
    public void receive06(Object msg) {
        log.info("QUEUE02 receive direct message : {}" , msg);
    }*/

    @Autowired
    private IGoodsService goodsService;
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private IOrderService orderService;

    // 下单操作
    @RabbitListener(queues = "seckillQueue")
    public void receive(String message) {
        log.info("接受的消息：" + message);
        SecKillMessage secKillMessage = JsonUtil.jsonStr2Object(message, SecKillMessage.class);
        Long goodId = secKillMessage.getGoodId();
        User user = secKillMessage.getUser();
        // 然后开始判断库存
        GoodsVO goodsVO = goodsService.findGoodsVoByGoodsId(goodId);
        if (goodsVO.getStockCount() < 1) {
            return;
        }

        // 判断是否重复抢购
        SeckillOrder seckillOrder =
                (SeckillOrder) redisTemplate.opsForValue().get("order:" + user.getId() + ":" + goodId);
        if (seckillOrder != null) {
            return;
        }

        // 再不存在库存不足以及重复抢购的条件下 开始抢购
        orderService.secKill(user, goodsVO);

    }

}
